<template>
  <el-card class="task-card" :body-style="{ padding: '24px' }">
    <div class="task-header">
      <div class="task-info">
        <h3 class="task-title">{{ task.skillName }}</h3>
        <el-tag 
          :type="getTaskProgressType" 
          class="task-status-tag"
          effect="light"
        >
          {{ getTaskProgressText }}
        </el-tag>
      </div>
      <div class="task-actions">
        <el-button 
          type="primary" 
          @click="$emit('show-detail', task)"
          class="action-button"
        >
          查看详情
        </el-button>
      </div>
    </div>

    <div class="task-description" v-if="task.description">
      <p>{{ task.description }}</p>
    </div>

    <div class="task-progress">
      <el-progress 
        :percentage="calculateTaskProgress" 
        :status="getTaskProgressStatus"
        :stroke-width="12"
        class="progress-bar"
      />
      <div class="progress-info">
        <span class="progress-text">已完成 {{ getCompletedNodesCount }} 个节点</span>
        <span class="progress-text">总计 {{ getTotalNodesCount }} 个节点</span>
      </div>
    </div>

    <!-- <div class="stages-list">
      <el-collapse>
        <el-collapse-item 
          v-for="stage in task.stages" 
          :key="stage.id"
          :title="`${stage.name} (${getStageProgress(stage)}%)`"
        >
          <div class="stage-content">
            <p class="stage-description">{{ stage.description }}</p>
            <div class="nodes-grid">
              <div 
                v-for="node in stage.nodes" 
                :key="node.id"
                class="node-item"
                :class="{ 'completed': node.completed }"
                @click="toggleNode(node)"
              >
                <span>{{ node.name }}</span>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div> -->
  </el-card>
</template>

<script setup>
import { computed, onUnmounted } from 'vue'
import { Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateSkill, deleteSkill } from '@/api/skill'
import { useDebounce } from '@/utils/debounce'

const props = defineProps({
  task: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['show-detail', 'archive', 'update', 'refresh'])

// 使用防抖工具
const { debouncedFn: debouncedUpdate, clear: clearDebounce } = useDebounce(async (node) => {
  try {
    await updateSkill({
      id: props.task.id,
      stages: JSON.stringify(props.task.stages)
    })
    
    if (isTaskCompletable.value) {
      emit('archive', props.task)
    }
  } catch (error) {
    node.completed = !node.completed
    ElMessage.error('更新任务状态失败')
    console.error('更新任务状态失败:', error)
  }
})

// 计算属性
const calculateTaskProgress = computed(() => {
  const totalNodes = getTotalNodesCount.value
  const completedNodes = getCompletedNodesCount.value
  return Math.round((completedNodes / totalNodes) * 100)
})

const getTaskProgressStatus = computed(() => {
  const progress = calculateTaskProgress.value
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return ''
})

const getTaskProgressType = computed(() => {
  const progress = calculateTaskProgress.value
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return 'info'
})

const getTaskProgressText = computed(() => {
  const progress = calculateTaskProgress.value
  if (progress >= 100) return '已完成'
  if (progress >= 50) return '进行中'
  return '刚开始'
})

const isTaskCompletable = computed(() => {
  return calculateTaskProgress.value === 100
})

const getTotalNodesCount = computed(() => {
  return props.task.stageVos.reduce((total, stage) => total + stage.nodes.length, 0)
})

const getCompletedNodesCount = computed(() => {
  return props.task.stageVos.reduce((total, stage) => {
    return total + stage.nodes.filter(node => node.completed).length
  }, 0)
})

// 方法
const getStageProgress = (stage) => {
  const total = stage.nodes.length
  const completed = stage.nodes.filter(node => node.completed).length
  return Math.round((completed / total) * 100)
}

const toggleNode = async (node) => {
  node.completed = !node.completed
  debouncedUpdate(node)
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deleteSkill(props.task.id)
    ElMessage.success('删除成功')
    emit('refresh')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 组件卸载时清理
onUnmounted(() => {
  clearDebounce()
})
</script>

<style scoped>
.task-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.task-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 28px;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.task-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.task-status-tag {
  font-size: 13px;
  padding: 4px 12px;
  border-radius: 6px;
}

.task-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  padding: 8px 20px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.task-progress {
  margin-bottom: 0;
}

.progress-bar {
  margin-bottom: 12px;
}

.progress-bar :deep(.el-progress-bar__outer) {
  border-radius: 6px;
}

.progress-bar :deep(.el-progress-bar__inner) {
  border-radius: 6px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

.progress-text {
  font-size: 14px;
  color: #606266;
}

.task-description {
  margin: 12px 0 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.task-description p {
  margin: 0;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .task-card {
    margin-bottom: 16px;
  }

  .task-header {
    flex-direction: column;
    gap: 16px;
    margin-bottom: 20px;
  }

  .task-info {
    width: 100%;
    justify-content: space-between;
  }

  .task-title {
    font-size: 16px;
  }

  .task-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .action-button {
    padding: 6px 16px;
    font-size: 13px;
  }

  .progress-text {
    font-size: 13px;
  }

  .task-description {
    margin: 8px 0 16px;
    font-size: 13px;
  }
}

/* 添加点击反馈动画 */
@keyframes click-feedback {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1);
  }
}

.node-item:active {
  animation: click-feedback 0.2s ease;
}
</style> 